package su.samlib.informer.utils.updaters.samizdatupdaters;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import su.samlib.informer.model.Author;
import su.samlib.informer.model.Book;
import su.samlib.informer.utils.updaters.AbstractBooksUpdater;

public class SamizdatPlainTextBooksUpdater extends AbstractBooksUpdater {

    private static final String TEXT_PATTERN = "<DL><DT><li>(?:<font.*?>.*?</font>)?\\s*(<b>(.*?)\\s*</b>\\s*)?<A HREF=(.*?)><b>\\s*(.*?)\\s*</b></A>.*?<b>(\\d+)k</b>.*?<small>(?:Оценка:<b>((\\d+(?:\\.\\d+)?).*?)</b>.*?)?\\s*\"(.*?)\"\\s*(.*?)?\\s*(?:<A HREF=\"(.*?)\">Комментарии:\\s*((\\d+).*?)</A>\\s*)?</small>.*?(?:<br><DD><font color=\"#555555\">(.*?))?</font></DL>";
    private static final Pattern textPattern = Pattern.compile(TEXT_PATTERN);
    private static final int LINK_TO_TEXT = 3;
    private static final int DESCRIPTION = 13;
    private static final int SIZE_OF_TEXT = 5;
    private static final int SECTION = 8;
    private static final int GENRES = 9;
    private static final int NAME_OF_TEXT = 4;
    private final List<Book> texts = new ArrayList<Book>();
    private Author author;

    @Override
    public void setAuthor(final Author a) {
        this.author = a;
    }

    private Book parseAuthorText(Matcher match) {
        Book tmpBook = new Book();
        tmpBook.setBookUri(match.group(LINK_TO_TEXT).trim());
        tmpBook.setBookTitle(unescapeAndCleanHtml(match.group(NAME_OF_TEXT).trim()));
        tmpBook.setBookSize(new Integer(match.group(SIZE_OF_TEXT)));
        tmpBook.setBookDescription(unescapeAndCleanHtml(match.group(DESCRIPTION).trim()));
        return tmpBook;
    }

    @Override
    protected URL getRequestURL() {
        URL authorUrl = null;
        try {
            authorUrl = new URL(getAuthorUrl(author) + "indexdate.shtml");
        } catch (MalformedURLException ex) {
            Logger.getLogger(SamizdatPlainTextBooksUpdater.class.getName()).log(Level.SEVERE, null, ex);
        }
        return authorUrl;
    }

    @Override
    public List<Book> getBooks() {
        String authorPage = getAuthorPage();

        Matcher m = textPattern.matcher(authorPage);
        boolean matchFound = m.find();
        while (matchFound) {
            Book tmpAuthorText = parseAuthorText(m);
            texts.add(tmpAuthorText);
            matchFound = m.find();
        }

        return texts;

    }
}
